package com.example.java_chatroom.api;

import com.example.java_chatroom.model.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HandshakeCompletedEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//获取会话
@RestController
public class MessageSessionAPI {
    @Resource
    private MessageSessionMapper messageSessionMapper;

    @Resource
    private MessageMapper messageMapper;

    @GetMapping("/sessionList")
    @ResponseBody
    public Object getMessageSessionList(HttpServletRequest req){
        List<MessageSession> messageSessionList = new ArrayList<>();
        //1.获取当前用户的userId（从spring中的session中获得）
        HttpSession session =  req.getSession(false);
        if(session == null){
            System.out.println("[getMessageSessionList] session == null");
            return messageSessionList;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            System.out.println("[getMessageSessionList] user == null");
            return messageSessionList;
        }
        //2.根据userId查询数据库，查出来有哪些会话id
        List<Integer> sessionIdList = messageSessionMapper.getSessionIdsByUserId(user.getUserId());
        for (int sessionId : sessionIdList){
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);
            //3。遍历会话id，查询出每个会话里涉及的好友都有谁
            List<Friend> friends = messageSessionMapper.getFriendsBySessionId(sessionId, user.getUserId());
            messageSession.setFriends(friends);
            //4.遍历会话id，查询出每个会话的最后一条消息
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            if (lastMessage == null){
                messageSession.setLastMessage("");
            }else{
                messageSession.setLastMessage(lastMessage);
            }
            messageSessionList.add(messageSession);
        }
        //最终目标是构建出一个MessageSession对象数组
        return messageSessionList;
    }
    @PostMapping("/session")
    @ResponseBody
    @Transactional
    public Object addMessageSession (int toUserId, @SessionAttribute("user") User user){
        HashMap<String,Integer> resp = new HashMap<>();
        //进行数据库的插入操作
        //先给 messageSession 表里插入记录，使用这个参数的目的主要是为了获取到会话的sessionId
        MessageSession messageSession = new MessageSession();
        messageSessionMapper.addMessageSession(messageSession);
        //2.给 message_session_user 表插入记录
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId());
        item1.setUserId(user.getUserId());
        messageSessionMapper.addMessageSessionUser(item1);
        //3.给message_session_user表插入记录
        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setSessionId(messageSession.getSessionId());
        item2.setUserId(toUserId);
        messageSessionMapper.addMessageSessionUser(item2);

        System.out.println("[addMessageSession] 新增会话成功！sessionId=" +messageSession.getSessionId()
        + "userId1=" + user.getUserId()+"userId2" +toUserId);

        resp.put("sessionId", messageSession.getSessionId());

        return resp;
    }
}
